package com.nelson.musicplayer.business.home

import android.content.Context
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.vlayout.DelegateAdapter
import com.alibaba.android.vlayout.VirtualLayoutManager
import com.nelson.musicplayer.R
import com.nelson.musicplayer.base.BaseFragment
import com.nelson.musicplayer.business.home.adapter.BannerAdapter
import com.nelson.musicplayer.business.home.adapter.HomeSongAdapter
import com.nelson.musicplayer.databinding.FragmentHomeBinding
import com.nelson.musicplayer.source.Status
import com.nelson.musicplayer.source.bean.HomeData
import com.nelson.musicplayer.util.toast
import com.nelson.musicplayer.widget.CommonLoadingDialog

/**
 * @author nelson
 * @since 2020-07-25
 */
class HomeFragment : BaseFragment<FragmentHomeBinding>() {

    enum class ItemViewType(var type: Int) {
        BIG_PIC(0), GROUP_SONG(1)
    }

    private lateinit var mDelegateAdapter: DelegateAdapter
    private var mBannerAdapter = BannerAdapter(ItemViewType.BIG_PIC.type)
    private var mGroupSongAdapter = HomeSongAdapter(ItemViewType.GROUP_SONG.type)

    private val mViewModel: HomeViewModel by viewModels {
        ViewModelProvider.NewInstanceFactory()
    }

    private lateinit var mLoadingDialog: CommonLoadingDialog

    override fun onAttach(context: Context) {
        super.onAttach(context)
        mLoadingDialog = CommonLoadingDialog(requireContext())
    }

    override fun initData() {
        initView()
        fetchData()
    }

    private fun fetchData() {
        mViewModel.fetchHomeData().observe(this, Observer {
            when (it.status) {
                Status.LOADING -> {
                    mLoadingDialog.show()
                }
                Status.SUCCESS -> {
                    mLoadingDialog.dismiss()
                    refreshView(it.data)
                }
                Status.ERROR -> {
                    toast(it.msg)
                    mLoadingDialog.dismiss()
                }
            }
        })
    }

    private fun refreshView(data: HomeData?) {
        data?.let {
            mBannerAdapter.setData(data.banner)
            mGroupSongAdapter.setData(data.data)
        }
    }

    private fun initView() {
        val virtualLayoutManager = VirtualLayoutManager(requireContext())
        mViewDataBinding.recycleView.layoutManager = virtualLayoutManager
        val viewPool = RecyclerView.RecycledViewPool()
        mViewDataBinding.recycleView.setRecycledViewPool(viewPool)
        viewPool.setMaxRecycledViews(0, 10)
        mDelegateAdapter = DelegateAdapter(virtualLayoutManager, true)

        mDelegateAdapter.addAdapter(mBannerAdapter)
        mDelegateAdapter.addAdapter(mGroupSongAdapter)

        mViewDataBinding.recycleView.adapter = mDelegateAdapter
    }

    override fun getContentView(): Int = R.layout.fragment_home
}